import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from gui import Ui_Ncbi
from PyQt5 import QtCore
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)


class MyMainForm(QMainWindow,Ui_Ncbi):
    print("fuck class")
    def __init__(self,parent=None):
        super(MyMainForm,self).__init__(parent)
        self.setupUi(self)

        self.conver_pushButton.clicked.connect(self.convert)
        self.apply_pushButton.clicked.connect(self.extent_gene)
        self.get_geng_pushButton.clicked.connect(self.get_url)
        self.save_pushButton.clicked.connect(self.save_gb)
        self.proxy_lineEdit.hide()
        self.proxy_checkBox.stateChanged.connect(self.proxy)
        self.get_lyric()

        # 随机诗句
    def get_lyric(self):
        from requests import get
        try:
            lyric =  get ('https://v1.hitokoto.cn/?c=i', timeout=20)
            lyric = lyric.json()
            text = 'NCBI Gene Downloader' + '\n\n\n' + 'By Qiqin Mo' + '\n\n\n' + '' + lyric['hitokoto'] + "\n"
            text = text + "\n" + "——" + "《" + lyric["from"] + "》" + '，' + lyric["from_who"]
            self.textBrowser.setText(text)

        except:
            lyric = ''
            text = 'NCBI Gene Downloader' + '\n\n\n' + 'By Qiqin Mo' + '\n\n\n' + ''

        self.textBrowser.setText(text)





    def convert(self):
        print('converting...')
        from re import search
        location = str(self.location_lineEdit.text())
        #print(location)
        locus: str = search('NC_0+[0-9]+\.[0-9]+', location).group()
        print(locus)
        start = search('\([0-9]+\.', location).group().replace('(', '').replace('.', '')
        stop = search('\.\.[0-9]+', location).group()
        # print(stop)
        stop = search('[0-9]+', stop).group()
        complement = search('complement', location)


        if complement:
            strand = "&strand=true"
            print('comlement')
            self.checkBox.setCheckState(2)
        else:
            strand = ''

        print(locus,start,stop)
        self.chromosome_lineEdit.setText(locus)
        self.start_lineEdit.setText(start)
        self.stop_lineEdit.setText(stop)


    def extent_gene(self):
        start = self.start_lineEdit.text()
        stop = self.stop_lineEdit.text()
        print(stop)
        up = self.upstream_lineEdit.text()
        down = self.downstream_lineEdit.text()

        check_state =  self.checkBox.checkState()
        if check_state:
            start = int(start) + int(up)
            stop = int(stop) - int(down)
        else:
            start= int(start) - int(up)
            stop = int(stop) + int(down)
            print(stop)
        print('done')
        self.start_lineEdit.setText(str(start))
        self.stop_lineEdit.setText(str(stop))


    def get_url(self):

        locus = self.chromosome_lineEdit.text()
        start = self.start_lineEdit.text()
        stop = self.stop_lineEdit.text()
        check_state = self.checkBox.checkState()
        strand = ''

        if check_state:
            print('com')
            strand = "&strand=true"
        else:
            strand = ''
        url = "https://www.ncbi.nlm.nih.gov/nuccore/" + locus + "?from=" + start + "&to=" + stop + "&report=genebank" + strand
        print(url)
        self.url_textBrowser.setText(url)

    def save_gb(self):
        print('---------save gb---------')
        self.textBrowser.setText('Downloading...')
        name = self.save_path_lineEdit.text() + '.gb'

        locus = self.chromosome_lineEdit.text()
        start = self.start_lineEdit.text()
        stop = self.stop_lineEdit.text()
        check_state = self.checkBox.checkState()
        strand = ''

        if check_state:
            print('com')
            strand = "&strand=true"
        else:
            strand = ''
        from requests import get
        from re import search, sub
        from time import sleep
        #
        print('setting proxy')
        #proxies = {"http": "http://127.0.0.1:10809", "https": "http://127.0.0.1:10809" }

        if self.proxy_checkBox.checkState():
            print('using proxy')
            proxy = self.proxy_lineEdit.text()
        else:
            print('not using proxy')
            proxy = ''

        proxies = {"http": proxy, "https": proxy}

        print('proxies is ', proxies)

        url = "https://www.ncbi.nlm.nih.gov/nuccore/" + locus + "?from=" + start + "&to=" + stop + "&report=genebank" + strand
        print('You can browse the ture url:\n' + url + '\n')
        self.url_textBrowser.setText(url)
        page_uid = get(url, proxies=proxies, timeout=20)
        uid = search('ncbi_uid=[0-9]+', page_uid.content.decode('utf-8')).group().replace('ncbi_uid=', '')
        print('uid is ',uid)
        genebank_url = "https://www.ncbi.nlm.nih.gov/sviewer/viewer.fcgi?id=" + uid + "&db=nuccore&report=genbank&&from=" + start + "&to=" + stop + "&retmode=html&withmarkup=on&tool=portal&log$=seqview&maxdownloadsize=1000000"
        #print(url)


        # print(url)
        try:
            print('start downloading')

            #page = get(genebank_url,proxies=proxies).content.decode('utf-8')

            #print(page)
            page = get(genebank_url,proxies=proxies,timeout=20).content.decode('utf-8')
            print('page got!')
            result = search('<pre(.|\n)*/pre>', page).group()
            gb = sub('<script.*/script>', '', result)
            gb = sub('<.*?>', '', gb)

            self.textBrowser.setText(gb)
            print('start writting')
            #input('continue?')


        except Exception as e:
            print(e)
            self.textBrowser.setText('Download failed')
            gb = 'fial'

        with open(name, 'w') as my_open:
            my_open.write(gb)
            my_open.write('\n')
            my_open.close
        print('GeneBank file saved as ' + name)

    def proxy(self):

        if self.proxy_checkBox.checkState():
            self.proxy_lineEdit.show()

        else:
            self.proxy_lineEdit.hide()










if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWin = MyMainForm()
    myWin.show()
    sys.exit(app.exec_())
